package com.wyh.service.serviceImpl.appservieripml;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wyh.common.enums.ResultCodeEnum;
import com.wyh.common.exception.CustomException;
import com.wyh.common.exception.ResourceNotFoundException;

import com.wyh.domain.dto.gfive.LoginUser;
import com.wyh.domain.dto.groupfour.chargeIndexDTO.ClaimOnCreditDTO;
import com.wyh.domain.dto.groupfour.chargeIndexDTO.ClaimOnCreditPageDTO;
import com.wyh.domain.dto.groupfour.chargeIndexDTO.CustomerInfoPageDTO;

import com.wyh.domain.po.gfive.User;
import com.wyh.domain.vo.gruopfour.chargeIndexVO.*;
import com.wyh.domain.vo.gruopfour.threemeterVO.PageResult;
import com.wyh.mapper.appmapper.ChargeIndexMapper;
import com.wyh.service.appservice.ChargeIndexService;
import com.wyh.service.appservice.ChargeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import static com.wyh.common.enums.FindResourceEnum.HOUSE_TYPE;
import static com.wyh.common.enums.FindResourceEnum.RENTED;
import static com.wyh.common.enums.ResultCodeEnum.*;


@Service
@Slf4j
public class ChargeIndexServiceImpl implements ChargeIndexService {
    @Autowired
    private ChargeIndexMapper chargeIndexMapper;
    @Autowired
    private ChargeService chargeService;


    //     获取SecurityContext中的Authentication对象
    private static User getAdminUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            // 获取用户信息
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            return loginUser.getUser();
        } else {
            throw new CustomException(ResultCodeEnum.USER_NOT_LOGIN);
        }
    }

    @Override
    public AccountIndexVO getAccountIndex(Integer id) {
        if (id == null || id == 0){
            throw new CustomException(PARAM_ERROR);
        }
        log.info("获取到的参数id:"+id);
        AccountIndexVO projectAccountVo = chargeIndexMapper.getProjectAccountById(id);
        if (projectAccountVo.getProjectAccount() == 0)
        {
         throw new ResourceNotFoundException(ResultCodeEnum.PROJECT_NOT_FOUND);
        }
        List<Integer> allResourceIds = chargeService.getAllResourceIds(2 );
        System.out.println("获取到的参数allResourceIds:"+allResourceIds);
        if (  allResourceIds == null || allResourceIds.isEmpty() ){
            AccountIndexVO accountIndexVO = new AccountIndexVO();
            accountIndexVO.setProjectAccount(projectAccountVo.getProjectAccount());
            accountIndexVO.setOwnerAccount(0);
            accountIndexVO.setTenantAccount(0);
            return accountIndexVO;
        }
        AccountIndexVO ownerAndTenantAccountVo = chargeIndexMapper.getOwnerAndTenantAccountById(allResourceIds);
        AccountIndexVO accountIndexVO = new AccountIndexVO();
        accountIndexVO.setProjectAccount(projectAccountVo.getProjectAccount());
        accountIndexVO.setOwnerAccount(ownerAndTenantAccountVo.getOwnerAccount());
        accountIndexVO.setTenantAccount(ownerAndTenantAccountVo.getTenantAccount());
        return accountIndexVO;
    }

    @Override
    public DoTaskIndexVO getDoTaskIndex(Integer id) {
        Integer userid = getAdminUser().getId();
        if (id == null || id == 0) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        log.info("获取到的参数id:" + id);
        List<Integer> allResourceIds = chargeService.getAllResourceIds(2);
        System.out.println("获取到的参数allResourceIds:" + allResourceIds);
        if (allResourceIds == null ||  allResourceIds.isEmpty() ) {
            throw new CustomException(ResultCodeEnum.RESOURCE_NOT_ERROR);
        }
        List<Integer> allCustomerIds = chargeIndexMapper.getDistinctCustomerIds(allResourceIds);
        if (allCustomerIds == null || allCustomerIds.isEmpty())
        {
            throw new CustomException(ResultCodeEnum.CUSTOMER_NOT_ERROR);
        }
        DoTaskIndexVO PendingMoneny = chargeIndexMapper.getPendingMonenyById(allCustomerIds);
        DoTaskIndexVO unclaimedPaymentsCount = chargeIndexMapper.getUnclaimedPaymentsCount(allCustomerIds);
        DoTaskIndexVO refundAmount = chargeIndexMapper.getRefundById(allCustomerIds);
        //TODO  选取每个月的1号
//        LocalDate currentDate = LocalDate.now().withDayOfMonth(1);
//        java.sql.Date sqlDate = java.sql.Date.valueOf(currentDate);
        LocalDateTime currentDate = LocalDateTime.now();
        LocalDateTime sqlDate = currentDate.withDayOfMonth(1).withHour(0).withMinute(0).withSecond(0).withNano(0);
        System.out.println(currentDate);
//        List<Integer> allResourceIds1 = chargeService.getAllResourceIds(2);
//        System.out.println(allResourceIds1.size() + "---资源id0");
//        int alredyCount = chargeIndexMapper.countReadySumByReadingTime(allResourceIds1, sqlDate);
        List<Integer> resourceIds = chargeService.getAllResourceIds(HOUSE_TYPE.getCode(), RENTED.getCode());
        Integer sumCount = chargeIndexMapper.countSumByReadingTime(userid, sqlDate);
//                int requireCount = sumCount - alredyCount;
        if (sumCount == null){
            sumCount = 0;
        }
        int requireCount = sumCount;
        DoTaskIndexVO doTaskIndexVO = new DoTaskIndexVO();
        doTaskIndexVO.setPendingAmount(PendingMoneny.getPendingAmount());
        doTaskIndexVO.setRefundCount(refundAmount.getRefundCount());
        doTaskIndexVO.setClaimCount(unclaimedPaymentsCount.getClaimCount());
        doTaskIndexVO.setMeterCount(requireCount);
        return doTaskIndexVO;
    }

    @Override
    public UserOrganizationNameVO getUserWithOrganizationNames() {

//        return Result.error();
        //TODO  从security获取用户id
        Integer userId = getAdminUser().getId();
        OrganizationNamesVO namesVO = chargeIndexMapper.getUserWithOrganizationNames(userId);
        if (namesVO.getAName() == null) {
            throw new CustomException(SYSTEM_ERROR.getCode(), "组织名称为空");
        }
        if (namesVO.getUserName()==null){
            throw new CustomException(SYSTEM_ERROR.getCode(), "用户名为空");
        }
        String names = concatenateOrganizationNames(namesVO);
        UserOrganizationNameVO namesVO1 = new UserOrganizationNameVO();
        namesVO1.setUserName(namesVO.getUserName());
        namesVO1.setPName(names);
        return namesVO1;
    }

    @Override
    public PageResult<ClaimOnCreditVO>  getClaimOnCredit(ClaimOnCreditPageDTO claimOnCreditPage) {
        if (claimOnCreditPage.getCurrentPage() == null || claimOnCreditPage.getCurrentPage() == 0) {
            claimOnCreditPage.setCurrentPage(1);
        }
        if (claimOnCreditPage.getPageSize() == null || claimOnCreditPage.getPageSize() == 0){
            claimOnCreditPage.setPageSize(6);
        }
        log.info("获取到的参数claimOnCreditPage:" + claimOnCreditPage);
        List<Integer> allResourceIds = chargeService.getAllResourceIds(2);
        if (allResourceIds == null || allResourceIds.isEmpty()){
            throw new ResourceNotFoundException(RESOURCE_NOT_ERROR.getCode(), "没有资源");
        }
        List<Integer> allCustomerIds = chargeIndexMapper.getDistinctCustomerIds(allResourceIds);
        if (allCustomerIds == null || allCustomerIds.isEmpty()){
            throw new ResourceNotFoundException(CUSTOMER_NOT_ERROR.getCode(), "没有客户");
        }
        PageHelper.startPage(claimOnCreditPage.getCurrentPage(), claimOnCreditPage.getPageSize());
        Page<ClaimOnCreditVO> page = chargeIndexMapper.getPaymentRecordsByCustomerIds(allCustomerIds,claimOnCreditPage);
        if ( page == null || page.isEmpty()) {
            throw new ResourceNotFoundException(DATA_NOT_ERROR.getCode(), "没有需要挂账认领的客户");
        }
            return new PageResult<>(page.getTotal(), page.getResult());
        }

    @Override
    public PageResult<CustomerNameVO> findCustomersByNameAndTelephone(CustomerInfoPageDTO customerInfoPage) {
        if (customerInfoPage.getCurrentPage() == null || customerInfoPage.getPageSize() == 0)
        {
            customerInfoPage.setCurrentPage(1);
        }
        if (customerInfoPage.getPageSize() == null || customerInfoPage.getPageSize() == 0)
        {
            customerInfoPage.setPageSize(6);
        }
        log.info("获取到的参数customerInfoPage:" + customerInfoPage);
        List<Integer> allResourceIds = chargeService.getAllResourceIds(2);
        if (allResourceIds == null || allResourceIds.isEmpty()){
            throw new ResourceNotFoundException(RESOURCE_NOT_ERROR.getCode(), "没有资源");
        }
        PageHelper.startPage(customerInfoPage.getCurrentPage(), customerInfoPage.getPageSize());
        Page<CustomerNameVO> page = chargeIndexMapper.findCustomersByNameAndTelephone(allResourceIds, customerInfoPage, customerInfoPage.getCustomerName(), customerInfoPage.getTelephone());
        System.out.println(page+"客户资源");
        if (page == null || page.isEmpty()){
            throw new ResourceNotFoundException(CUSTOMER_NOT_ERROR.getCode(), "没有客户");
        }

        return new PageResult<>(page.getTotal(),page.getResult() );
    }

    @Override
    public int updatePaymentrecords(ClaimOnCreditDTO claimOnCreditDTO) {
        if (claimOnCreditDTO.getCustomerid() == 0 || claimOnCreditDTO.getId() == 0 ) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        log.info("获取到参数", claimOnCreditDTO);
//        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//
//        if (authentication != null) {
//            // 获取用户信息
//            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
//            System.out.println("==============================================================================");
//            System.out.println(loginUser);
//        }
        Integer userId = getAdminUser().getId();
        claimOnCreditDTO.setUserid(userId);
        int i = chargeIndexMapper.updatePaymentrecords(claimOnCreditDTO);
        if (i > 0) {
            return i;
        }
        return 0;
    }

    @Override
    public ClaimOnCreditVO getSingleClaiming(Integer id) {
        if (id == null || id == 0) {
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        log.info("获取到参数id:", id);
        ClaimOnCreditVO claimOnCreditVO = chargeIndexMapper.getSingleClaiming(id);
        if (claimOnCreditVO == null){
            throw new CustomException(ResultCodeEnum.DATA_NOT_ERROR);
        }
        return claimOnCreditVO;
    }

    @Override
    public CustomerNameVO getSingleCustomerInfo(Integer id) {
        if (id == null || id == 0){
            throw new CustomException(ResultCodeEnum.PARAM_ERROR);
        }
        CustomerNameVO singleCustomerInfo = chargeIndexMapper.getSingleCustomerInfo(id);

        return singleCustomerInfo;
    }

    public String concatenateOrganizationNames(OrganizationNamesVO namesVO) {
        StringBuilder concatenatedNames = new StringBuilder();
        List<String> names = Arrays.asList(namesVO.getDName(), namesVO.getCName(), namesVO.getBName(), namesVO.getAName());
        System.out.println(names);
        for (String name : names) {
            if (StringUtils.isNotBlank(name)) {
                concatenatedNames.append(name);
            }
        }
        return concatenatedNames.toString().trim(); // 无需再替换，因为我们没在末尾添加多余的分隔符
    }
}
